const { v4: uuidv4 } = require('uuid');
const logger = require('../config/logger');

// 请求日志中间件
const requestLogger = (req, res, next) => {
  // 生成唯一的请求ID
  req.requestId = uuidv4();
  
  // 记录请求开始时间
  req.startTime = Date.now();
  
  // 获取客户端IP
  req.ip = req.ip || 
           req.connection.remoteAddress || 
           req.socket.remoteAddress || 
           (req.connection.socket ? req.connection.socket.remoteAddress : null);
  
  // 记录请求信息
  const requestInfo = {
    requestId: req.requestId,
    method: req.method,
    url: req.originalUrl || req.url,
    ip: req.ip,
    userAgent: req.get('User-Agent'),
    contentType: req.get('Content-Type'),
    contentLength: req.get('Content-Length'),
    referer: req.get('Referer'),
    timestamp: new Date().toISOString()
  };
  
  // 在开发环境记录请求体（排除敏感信息）
  if (process.env.NODE_ENV === 'development' && req.body) {
    const sanitizedBody = { ...req.body };
    
    // 移除敏感字段
    const sensitiveFields = ['password', 'token', 'secret', 'key', 'auth'];
    sensitiveFields.forEach(field => {
      if (sanitizedBody[field]) {
        sanitizedBody[field] = '[REDACTED]';
      }
    });
    
    requestInfo.body = sanitizedBody;
  }
  
  logger.info('Request Started', requestInfo);
  
  // 监听响应完成事件
  res.on('finish', () => {
    const responseTime = Date.now() - req.startTime;
    
    const responseInfo = {
      requestId: req.requestId,
      method: req.method,
      url: req.originalUrl || req.url,
      statusCode: res.statusCode,
      responseTime: `${responseTime}ms`,
      contentLength: res.get('Content-Length'),
      ip: req.ip,
      userAgent: req.get('User-Agent'),
      userId: req.user?.id,
      timestamp: new Date().toISOString()
    };
    
    // 根据状态码选择日志级别
    if (res.statusCode >= 500) {
      logger.error('Request Completed', responseInfo);
    } else if (res.statusCode >= 400) {
      logger.warn('Request Completed', responseInfo);
    } else {
      logger.info('Request Completed', responseInfo);
    }
  });
  
  // 监听响应关闭事件（客户端断开连接）
  res.on('close', () => {
    if (!res.finished) {
      const responseTime = Date.now() - req.startTime;
      
      logger.warn('Request Aborted', {
        requestId: req.requestId,
        method: req.method,
        url: req.originalUrl || req.url,
        responseTime: `${responseTime}ms`,
        ip: req.ip,
        userId: req.user?.id,
        timestamp: new Date().toISOString()
      });
    }
  });
  
  next();
};

module.exports = requestLogger;